package com.shine.app.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.shine.app.AppManager;
import com.shine.app.BaseActivity;
import com.shine.app.R;
import com.shine.app.bean.UpdateUserProfile;
import com.shine.app.bean.UserBean;
import com.shine.app.bean.UserInfoBean;
import com.shine.app.bean.request.UpdateProfileBean;
import com.shine.app.bean.responses.UpdateUserProfileResponse;
import com.shine.app.commons.StringUtils;
import com.shine.app.commons.UIHelper;
import com.shine.app.inject.InjectView;
import com.shine.app.inject.Injector;

public class ViewMyAccountProfileActivity extends BaseActivity implements
		OnClickListener {

	@InjectView(R.id.head_back)
	private ImageView gobackImageView;
	@InjectView(R.id.user)
	private EditText userEditText;
	@InjectView(R.id.head_name)
	private TextView nameTextView;
	@InjectView(R.id.name)
	private EditText firstNameEditText;
	@InjectView(R.id.last)
	private EditText lastNameEditText;
	@InjectView(R.id.address)
	private EditText addressEditText;
	@InjectView(R.id.city)
	private EditText cityEditText;
	@InjectView(R.id.state)
	private EditText stateEditText;
	@InjectView(R.id.zip)
	private EditText zipEditText;
	@InjectView(R.id.phone)
	private EditText phoneEditText;
	@InjectView(R.id.submit)
	private Button submitButton;
	@InjectView(R.id.progressBar)
	private ProgressBar progressBar;

	Handler profileHandler = new Handler() {
		public void handleMessage(Message message) {
			if (message.what == 1) {
				UpdateUserProfileResponse response = (UpdateUserProfileResponse) message.obj;
				UpdateUserProfile profileBean = response.getData();
				updateUserInfo(profileBean);
				UIHelper.toastDialog(ViewMyAccountProfileActivity.this,
						R.string.profilesuccess, R.string.msg_yes);
			} else if (message.what == 0) {
				UIHelper.toastDialog(ViewMyAccountProfileActivity.this,
						R.string.profilefail, R.string.msg_yes);
			} else if (message.what == -1) {
				Exception exception = (Exception) message.obj;
				UIHelper.toastDialogs(ViewMyAccountProfileActivity.this,
						exception.getMessage(), R.string.msg_yes);
			}
			resetViewStatus(true);
			initUserData();
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.viewaccount_profile);
		Injector.get(this).inject();
		initProfile();
	}

	private void updateUserInfo(UpdateUserProfile updateUserProfile) {
		UserInfoBean userInfoBean = appContext.getLoginInfo();
		UserBean userBean = userInfoBean.getUser();
		userBean.setEmail(updateUserProfile.getEmail());
		userBean.setFirstName(updateUserProfile.getFirstName());
		userBean.setLastName(updateUserProfile.getLastName());
		userBean.setPhoneNumber(updateUserProfile.getPhoneNumber());
		userBean.setMobileNumber(updateUserProfile.getMobileNumber());
		userBean.setCreated(updateUserProfile.getCreated());
		userBean.setGender(updateUserProfile.getGender());
		userBean.setDateOfBirth(updateUserProfile.getDateOfBirth());
		userBean.setAddress(updateUserProfile.getAddress());
		userBean.setAddress2(updateUserProfile.getAddress2());
		userBean.setCity(updateUserProfile.getCity());
		userBean.setStateCode(updateUserProfile.getStateCode());
		userBean.setZipCode(updateUserProfile.getZipCode());
		userBean.setCountry2IsoCode(updateUserProfile.getCountry2IsoCode());
		userBean.setHasPassword(true);
		userInfoBean.setUser(userBean);
		appContext.saveLoginInfo(userInfoBean);
	}

	private void initProfile() {
		progressBar.setVisibility(View.GONE);
		nameTextView.setText(R.string.account_editprofile);
		submitButton.setOnClickListener(this);
		gobackImageView.setOnClickListener(this);
		initUserData();
	}

	private void initUserData() {
		if (appContext.isLogin()) {
			UserBean userBean = appContext.getLoginInfo().getUser();
			if (userBean != null) {
				userEditText.setText(userBean.getEmail());
				firstNameEditText.setText(userBean.getFirstName());
				lastNameEditText.setText(userBean.getLastName());
				addressEditText.setText(userBean.getAddress());
				cityEditText.setText(userBean.getCity());
				stateEditText.setText(userBean.getStateCode());
				zipEditText.setText(userBean.getZipCode());
				phoneEditText.setText(userBean.getPhoneNumber());
			}
		}
	}

	private void updateProfile(final UpdateProfileBean bean) {
		resetViewStatus(false);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					UpdateUserProfileResponse response = appContext
							.updateUserProfile(bean);
					if (response != null) {
						if (response.isHasError()) {
							message.what = 0;
							message.obj = response;
						} else {
							message.what = 1;
							message.obj = response;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					message.what = -1;
					message.obj = e;
				}
				profileHandler.sendMessage(message);
			}
		}.start();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.head_back:
			AppManager.getAppManager().finishActivity();
			overridePendingTransition(R.anim.anim, R.anim.slide_out_down);
			break;

		case R.id.submit:
			submitButton.startAnimation(buttonAnimations);
			inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
			String firstName = getEditTextValues(firstNameEditText);
			String lastName = getEditTextValues(lastNameEditText);
			String email = getEditTextValues(userEditText);
			String address = getEditTextValues(addressEditText);
			String city = getEditTextValues(cityEditText);
			String state = getEditTextValues(stateEditText);
			String zip = getEditTextValues(zipEditText);
			String phone = getEditTextValues(phoneEditText);
			if (!validationProfile(firstName, lastName, email, address, city,
					state, zip, phone)) {
				return;
			}
			if (appContext.isLogin()) {
				UserBean user = appContext.getLoginInfo().getUser();
				String userId = user.getUserId();
				if (!StringUtils.isEmpty(userId)) {
					UpdateProfileBean profileBean = new UpdateProfileBean(
							userId, firstName, lastName, email, address, city,
							state, zip, phone);
					updateProfile(profileBean);
				}
			} else {
				UIHelper.showLogin(ViewMyAccountProfileActivity.this);
			}
			break;

		default:
			break;
		}
	}

	private boolean validationProfile(String firstName, String lastName,
			String email, String address, String city, String state,
			String zip, String phone) {
		if (StringUtils.isEmpty(email)) {
			UIHelper.toastDialog(this, R.string.msg_email_field_empty,
					R.string.msg_yes);
			return false;
		}
		if (!StringUtils.isEmail(email)) {
			UIHelper.toastDialog(this, R.string.msg_invalid_email_format,
					R.string.msg_yes);
			return false;
		}
		if (StringUtils.isEmpty(firstName)) {
			UIHelper.toastDialog(this, R.string.msg_first_field_empty,
					R.string.msg_yes);
			return false;
		}
		if (StringUtils.isEmpty(lastName)) {
			UIHelper.toastDialog(this, R.string.msg_last_field_empty,
					R.string.msg_yes);
			return false;
		}
		if (StringUtils.isEmpty(address)) {
			UIHelper.toastDialog(this, R.string.msg_address_field_empty,
					R.string.msg_yes);
			return false;
		}
		if (StringUtils.isEmpty(city)) {
			UIHelper.toastDialog(this, R.string.msg_city_field_empty,
					R.string.msg_yes);
			return false;
		}
		if (StringUtils.isEmpty(zip)) {
			UIHelper.toastDialog(this, R.string.msg_zip_field_empty,
					R.string.msg_yes);
			return false;
		}
		return true;
	}

	private void resetViewStatus(boolean flag) {
		if (flag) {
			progressBar.setVisibility(View.GONE);
		} else {
			progressBar.setVisibility(View.VISIBLE);
		}
		gobackImageView.setClickable(flag);
		submitButton.setClickable(flag);
		firstNameEditText.setEnabled(flag);
		lastNameEditText.setEnabled(flag);
		userEditText.setEnabled(flag);
		addressEditText.setEnabled(flag);
		cityEditText.setEnabled(flag);
		stateEditText.setEnabled(flag);
		zipEditText.setEnabled(flag);
		phoneEditText.setEnabled(flag);
	}
}
